package com.example.demovote.controller;


import com.example.demovote.entity.User;
import com.example.demovote.service.IUserService;
import com.example.demovote.vo.Result;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * <p>
 * 投票系统-用户表-4 前端控制器
 * </p>
 *
 * @author ly
 * @since 2024-03-18
 */
@RestController
@RequestMapping("/demovote/user")
public class UserController {

    @Resource
    IUserService userService;

    @RequestMapping("login")
    public Result login(String name, String pwd, HttpSession session) {
        Result res =  userService.login(name, pwd);
        if(res.getCode() == 1){
            // 用会话记录当前登录的用户数据
            session.setAttribute("loginedUser", res.getData());
            Object servletPath = session.getAttribute("servletPath");
            session.removeAttribute("servletPath");
            res.setData(servletPath);
        }
        return res;
    }

    @RequestMapping("myinfo")
    public Result getLoginedUser(HttpSession session){
        Object loginedUser = session.getAttribute("loginedUser");
        if(loginedUser==null){
            return new Result(0,"未登录！",null);
        } else {
            return new Result(1,"已登录！",loginedUser);
        }
    }

    // 退出
    @RequestMapping("logout")
    public ModelAndView logout(HttpSession session, ModelAndView mav){
        // 销毁会话
        session.invalidate();
        // 回到 index.html
        mav.setViewName("redirect:/index.html");
        return mav;
    }

    @RequestMapping("register")
    public Result register( User user, String repwd){
        return userService.register(user, repwd);
    }

}

